<template>
  <div class="database-explorer">
    <el-container style="height: 100%">
      <!-- 左侧数据库列表 -->
      <el-aside width="250px" class="database-sidebar">
        <div class="sidebar-header">
          <h4>{{ $t('explorer.databases') }}</h4>
          <div class="header-actions">
            <el-button icon="el-icon-plus" circle size="mini" @click="showCreateDatabaseDialog" :title="$t('explorer.createDatabase')" />
            <el-button icon="el-icon-refresh" circle size="mini" @click="loadDatabases" :title="$t('common.refresh')" />
          </div>
        </div>

        <!-- 搜索框和排序 -->
        <div class="database-search">
          <el-input
            v-model="databaseSearchQuery"
            :placeholder="$t('explorer.searchDatabase')"
            prefix-icon="el-icon-search"
            size="small"
            clearable
            @input="onDatabaseSearch"
          />

          <!-- 排序选择器 -->
          <div class="sort-selector">
            <el-select
              v-model="databaseSortOrder"
              size="small"
              @change="sortDatabases"
              :placeholder="$t('explorer.sortBy')"
            >
              <el-option
                :label="$t('explorer.sortByNameAsc')"
                value="name-asc"
              >
                <i class="el-icon-sort-up"></i> {{ $t('explorer.sortByNameAsc') }}
              </el-option>
              <el-option
                :label="$t('explorer.sortByNameDesc')"
                value="name-desc"
              >
                <i class="el-icon-sort-down"></i> {{ $t('explorer.sortByNameDesc') }}
              </el-option>
              <el-option
                :label="$t('explorer.sortByTimeNewest')"
                value="time-newest"
              >
                <i class="el-icon-time"></i> {{ $t('explorer.sortByTimeNewest') }}
              </el-option>
              <el-option
                :label="$t('explorer.sortByTimeOldest')"
                value="time-oldest"
              >
                <i class="el-icon-time"></i> {{ $t('explorer.sortByTimeOldest') }}
              </el-option>
            </el-select>
          </div>

          <div v-if="databaseSearchQuery && filteredDatabases.length === 0" class="search-no-result">
            {{ $t('explorer.noMatchingDatabases') }}
          </div>
        </div>

        <div class="database-list">
          <el-menu
            :default-active="currentDatabase"
            @select="selectDatabase"
          >
            <el-tooltip
              v-for="db in filteredDatabases"
              :key="db"
              :content="db"
              placement="right"
              :disabled="db.length <= 20"
            >
              <el-menu-item
                :index="db"
                class="database-item"
                @contextmenu.native.prevent="handleDatabaseRightClick($event, db)"
              >
                <i class="el-icon-folder"></i>
                <span class="database-name" v-html="highlightMatch(db)"></span>
              </el-menu-item>
            </el-tooltip>
          </el-menu>

          <!-- 数据库数量统计 -->
          <div v-if="databases.length > 0" class="database-count">
            <span v-if="databaseSearchQuery">
              {{ filteredDatabases.length }} / {{ databases.length }}
            </span>
            <span v-else>
              {{ databases.length }} {{ $t('explorer.databases') }}
            </span>
          </div>
        </div>
        
        <!-- Database context menu -->
        <div
          v-if="contextMenu.visible"
          class="context-menu"
          :style="{ left: contextMenu.x + 'px', top: contextMenu.y + 'px' }"
          @click.stop
        >
          <div class="context-menu-item" @click="deleteDatabase">
            <i class="el-icon-delete"></i> {{ $t('explorer.deleteDatabase') }}
          </div>
        </div>
      </el-aside>
      
      <!-- 右侧内容区 -->
      <el-container>
        <el-header height="auto" class="content-header">
          <div class="header-info">
            <div class="header-title">
              <h3>
                {{ currentDatabase || $t('common.selectDatabase') }}
                <span v-if="currentDatabase && currentMeasurement" class="measurement-name">
                  / {{ currentMeasurement }}
                </span>
              </h3>
            </div>
            <div v-if="currentDatabase" class="database-actions">
              <div class="action-group measurement-group">
                <label class="measurement-label">{{ $t('explorer.measurement') }}:</label>
                <el-select
                  v-model="currentMeasurement"
                  :placeholder="$t('common.selectMeasurement')"
                  @change="loadMeasurementData"
                  class="measurement-select"
                >
                  <el-option
                    v-for="measurement in measurements"
                    :key="measurement"
                    :label="measurement"
                    :value="measurement"
                  />
                </el-select>
                
                <el-button
                  v-if="currentMeasurement"
                  icon="el-icon-delete"
                  type="danger"
                  size="small"
                  @click="deleteMeasurement"
                >
                  {{ $t('common.delete') }}
                </el-button>
              </div>
              
              <div class="action-group">
                <el-button-group>
                  <el-button icon="el-icon-refresh" size="small" @click="refreshData">{{ $t('common.refresh') }}</el-button>
                  <el-button icon="el-icon-download" size="small" @click="exportCurrentData">{{ $t('common.export') }}</el-button>
                  <el-button 
                    v-if="tableData.length > 0" 
                    icon="el-icon-data-analysis" 
                    size="small" 
                    type="primary"
                    @click="visualizeData"
                  >
                    {{ $t('explorer.visualize') }}
                  </el-button>
                </el-button-group>
              </div>
            </div>
          </div>
        </el-header>
        
        <el-main class="content-main">
          <!-- 时间筛选器 -->
          <div v-if="currentMeasurement" class="time-filter-container">
            <div class="filter-row">
              <div class="filter-item">
                <span class="filter-label">{{ $t('explorer.startTime') }}:</span>
                <el-date-picker
                  v-model="timeFilter.startTime"
                  type="datetime"
                  :placeholder="$t('explorer.startTime')"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  size="small"
                  :picker-options="startPickerOptions"
                />
              </div>
              
              <div class="filter-item">
                <span class="filter-label">{{ $t('explorer.endTime') }}:</span>
                <el-date-picker
                  v-model="timeFilter.endTime"
                  type="datetime"
                  :placeholder="$t('explorer.endTime')"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  size="small"
                  :picker-options="endPickerOptions"
                />
              </div>
              
              <div class="filter-item">
                <span class="filter-label">{{ $t('explorer.limit') }}:</span>
                <el-input-number
                  v-model="querySettings.limit"
                  :min="1"
                  :max="100000"
                  :step="1000"
                  size="small"
                  style="width: 120px"
                />
              </div>
              
              <div class="filter-actions">
                <el-button type="primary" size="small" icon="el-icon-search" @click="applyTimeFilter">
                  {{ $t('explorer.applyFilter') }}
                </el-button>
                <el-button size="small" icon="el-icon-refresh-left" @click="resetFilter">
                  {{ $t('explorer.resetFilter') }}
                </el-button>
              </div>
            </div>
          </div>
          
          <!-- 数据表格 -->
          <div v-if="currentMeasurement" class="data-table-container">
            <div v-if="pagination.total > 0" class="table-info">
              <div class="info-left">
                {{ $t('explorer.showingRecords', {
                  start: (pagination.currentPage - 1) * pagination.pageSize + 1,
                  end: Math.min(pagination.currentPage * pagination.pageSize, pagination.total),
                  total: pagination.total
                }) }}
                <span style="margin-left: 10px;">
                  ({{ $t('explorer.limit') }}: {{ querySettings.limit }},
                  {{ timeFilter.startTime || timeFilter.endTime ? 'Filtered' : 'All data' }})
                </span>
              </div>
              <div class="info-right">
                <el-button
                  size="mini"
                  icon="el-icon-setting"
                  @click="showColumnSettings = true"
                  :title="$t('explorer.columnSettings')"
                >
                  {{ $t('explorer.columns') }}
                </el-button>
              </div>
            </div>
            <div class="table-wrapper">
              <el-table
                :data="tableData"
                v-loading="loading"
                border
                stripe
                height="100%"
                @sort-change="handleSortChange"
              >
              <el-table-column
                type="index"
                width="50"
                label="#"
                :index="indexMethod"
              />

              <el-table-column
                v-for="column in visibleColumns"
                :key="column"
                :prop="column"
                :label="column"
                :min-width="column === 'time' ? 240 : 120"
                sortable="custom"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  <span v-if="column === 'time'" class="time-cell">
                    {{ formatTime(scope.row[column]) }}
                  </span>
                  <span v-else>
                    {{ scope.row[column] }}
                  </span>
                </template>
              </el-table-column>
              </el-table>
            </div>
            
            <!-- 分页 -->
            <div class="pagination-wrapper">
              <el-pagination
                :key="'pagination-' + $i18n.locale"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pagination.currentPage"
                :page-sizes="[10, 20, 50, 100, 200, 500, 1000]"
                :page-size="pagination.pageSize"
                :total="pagination.total"
                layout="total, sizes, prev, pager, next, jumper"
              />
            </div>
          </div>
          
          <!-- 空状态 -->
          <el-empty v-else-if="currentDatabase && measurements.length === 0" :description="$t('explorer.noMeasurementsFound')" />
          <el-empty v-else-if="currentDatabase && !currentMeasurement" :description="$t('common.loading')" />
          <el-empty v-else :description="$t('common.selectDatabase')" />
        </el-main>
      </el-container>
    </el-container>
    
    <!-- Create Database Dialog -->
    <el-dialog :title="$t('explorer.createDatabase')" :visible.sync="showNewDatabaseDialog" width="400px">
      <el-form :model="newDatabaseForm" :rules="databaseRules" ref="databaseForm">
        <el-form-item :label="$t('explorer.databaseName')" prop="name">
          <el-input
            v-model="newDatabaseForm.name"
            :placeholder="$t('explorer.databaseName')"
            autofocus
          />
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="showNewDatabaseDialog = false">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="createDatabase" :loading="creating">
          {{ $t('common.create') }}
        </el-button>
      </span>
    </el-dialog>

    <!-- Column Settings Dialog -->
    <el-dialog
      :title="$t('explorer.columnSettings')"
      :visible.sync="showColumnSettings"
      width="500px"
      class="column-settings-dialog"
    >
      <div class="column-settings-content">
        <div class="settings-header">
          <el-input
            v-model="columnSearchQuery"
            :placeholder="$t('explorer.searchColumns')"
            prefix-icon="el-icon-search"
            size="small"
            clearable
            style="margin-bottom: 15px;"
          />
          <div class="quick-actions">
            <el-button size="mini" @click="selectAllColumns">{{ $t('explorer.selectAll') }}</el-button>
            <el-button size="mini" @click="deselectAllColumns">{{ $t('explorer.deselectAll') }}</el-button>
            <el-button size="mini" @click="resetColumnSettings">{{ $t('explorer.reset') }}</el-button>
          </div>
        </div>

        <div class="column-list">
          <el-checkbox-group v-model="selectedColumns">
            <div
              v-for="column in filteredTableColumns"
              :key="column"
              class="column-item"
            >
              <el-checkbox :label="column">
                <span class="column-label">{{ column }}</span>
                <el-tag v-if="column === 'time'" size="mini" type="info">{{ $t('explorer.timeField') }}</el-tag>
              </el-checkbox>
            </div>
          </el-checkbox-group>

          <div v-if="filteredTableColumns.length === 0" class="no-columns">
            {{ $t('explorer.noMatchingColumns') }}
          </div>
        </div>

        <div class="settings-footer">
          <div class="selected-count">
            {{ $t('explorer.selectedColumns', { count: selectedColumns.length, total: tableColumns.length }) }}
          </div>
        </div>
      </div>

      <span slot="footer">
        <el-button @click="cancelColumnSettings">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="applyColumnSettings">{{ $t('common.apply') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import influxdb from '@/utils/influxdb'
import Papa from 'papaparse'
import i18nMixin from '@/mixins/i18nMixin'

export default {
  name: 'DatabaseExplorer',
  mixins: [i18nMixin],
  
  data() {
    return {
      databases: [],
      databasesWithMeta: [], // 带有元数据的数据库列表
      databaseSearchQuery: '', // 数据库搜索关键词
      databaseSortOrder: 'name-asc', // 数据库排序方式
      currentDatabase: '',
      measurements: [],
      currentMeasurement: '',
      tableData: [],
      tableColumns: [],
      selectedColumns: [], // 用户选择显示的列
      columnSearchQuery: '', // 列搜索关键词
      showColumnSettings: false, // 显示列设置对话框
      loading: false,
      creating: false,
      pagination: {
        currentPage: 1,
        pageSize: 50,
        total: 0
      },
      showNewDatabaseDialog: false,
      querySettings: {
        limit: 10000
      },
      timeFilter: {
        startTime: null,
        endTime: null
      },
      sortConfig: {
        prop: null,
        order: null
      },
      newDatabaseForm: {
        name: ''
      },
      databaseRules: {
        name: [
          { required: true, message: 'Please enter database name', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9_]+$/, message: 'Only letters, numbers and underscore allowed', trigger: 'blur' }
        ]
      },
      contextMenu: {
        visible: false,
        x: 0,
        y: 0,
        database: null
      },
      startPickerOptions: {
        disabledDate: (time) => {
          if (this.timeFilter.endTime) {
            return time.getTime() > new Date(this.timeFilter.endTime).getTime()
          }
          return false
        }
      },
      endPickerOptions: {
        disabledDate: (time) => {
          if (this.timeFilter.startTime) {
            return time.getTime() < new Date(this.timeFilter.startTime).getTime()
          }
          return false
        }
      }
    }
  },
  
  computed: {
    ...mapState(['currentConnection']),

    // 过滤和排序后的数据库列表
    filteredDatabases() {
      let result = [...this.databases]

      // 应用搜索过滤
      if (this.databaseSearchQuery) {
        const query = this.databaseSearchQuery.toLowerCase().trim()
        result = result.filter(db =>
          db.toLowerCase().includes(query)
        )
      }

      // 应用排序
      return this.applySortToDatabases(result)
    },

    // 可见的列（根据用户选择）
    visibleColumns() {
      if (this.selectedColumns.length === 0) {
        return this.tableColumns
      }
      // 保持原始顺序
      return this.tableColumns.filter(col => this.selectedColumns.includes(col))
    },

    // 过滤后的列列表（用于列设置对话框）
    filteredTableColumns() {
      if (!this.columnSearchQuery) {
        return this.tableColumns
      }

      const query = this.columnSearchQuery.toLowerCase().trim()
      return this.tableColumns.filter(col =>
        col.toLowerCase().includes(query)
      )
    }
  },
  
  mounted() {
    if (!this.currentConnection) {
      this.$message.warning('Please connect to a database first')
      this.$router.push('/connections')
      return
    }
    
    this.loadDatabases()
    
    // Close context menu when clicking elsewhere
    document.addEventListener('click', this.closeContextMenu)
  },
  
  beforeDestroy() {
    document.removeEventListener('click', this.closeContextMenu)
  },
  
  methods: {
    async loadDatabases() {
      try {
        this.loading = true
        const dbs = await influxdb.getDatabases()
        this.databases = dbs

        // 加载数据库元数据（用于时间排序）
        await this.loadDatabasesMetadata()

        // Auto-select first database if none selected
        if (!this.currentDatabase && dbs.length > 0) {
          this.selectDatabase(dbs[0])
        }
      } catch (error) {
        this.$message.error('Failed to load databases: ' + error.message)
      } finally {
        this.loading = false
      }
    },

    async loadDatabasesMetadata() {
      // 为每个数据库加载元数据（最新数据时间）
      this.databasesWithMeta = await Promise.all(
        this.databases.map(async (dbName) => {
          try {
            // 查询最新的一条数据的时间
            const query = `SELECT * FROM /.*/ ORDER BY time DESC LIMIT 1`
            const results = await influxdb.executeQueryForDatabase(query, dbName)

            let latestTime = null
            if (results && results.length > 0 && results[0].time) {
              latestTime = new Date(results[0].time).getTime()
            }

            return {
              name: dbName,
              latestTime: latestTime
            }
          } catch (error) {
            // 如果查询失败（例如空数据库），返回 null 时间
            return {
              name: dbName,
              latestTime: null
            }
          }
        })
      )
    },

    applySortToDatabases(databases) {
      const sorted = [...databases]

      switch (this.databaseSortOrder) {
        case 'name-asc':
          return sorted.sort((a, b) => a.localeCompare(b))

        case 'name-desc':
          return sorted.sort((a, b) => b.localeCompare(a))

        case 'time-newest':
          // 按最新数据时间降序（最新的在前）
          return sorted.sort((a, b) => {
            const metaA = this.databasesWithMeta.find(m => m.name === a)
            const metaB = this.databasesWithMeta.find(m => m.name === b)
            const timeA = metaA?.latestTime || 0
            const timeB = metaB?.latestTime || 0
            return timeB - timeA
          })

        case 'time-oldest':
          // 按最新数据时间升序（最旧的在前）
          return sorted.sort((a, b) => {
            const metaA = this.databasesWithMeta.find(m => m.name === a)
            const metaB = this.databasesWithMeta.find(m => m.name === b)
            const timeA = metaA?.latestTime || Number.MAX_SAFE_INTEGER
            const timeB = metaB?.latestTime || Number.MAX_SAFE_INTEGER
            return timeA - timeB
          })

        default:
          return sorted
      }
    },

    sortDatabases() {
      // 触发 computed 属性重新计算
      // filteredDatabases 会自动应用新的排序
    },
    
    async selectDatabase(dbName) {
      this.currentDatabase = dbName
      this.currentMeasurement = ''
      this.tableData = []
      this.tableColumns = []
      
      // Load measurements for selected database
      await this.loadMeasurements(dbName)
    },
    
    async loadMeasurements(dbName) {
      try {
        this.loading = true
        const measurements = await influxdb.getMeasurementsForDatabase(dbName)
        this.measurements = measurements
        
        // Auto-select first measurement if available
        if (measurements && measurements.length > 0) {
          this.currentMeasurement = measurements[0]
          // Auto-load data for first measurement
          await this.loadMeasurementData()
        }
      } catch (error) {
        this.$message.error('Failed to load measurements: ' + error.message)
      } finally {
        this.loading = false
      }
    },
    
    async loadMeasurementData() {
      if (!this.currentMeasurement) return

      try {
        this.loading = true

        // Reset to first page when switching measurement
        this.pagination.currentPage = 1

        // Build query based on settings
        const query = this.buildQuery()
        const results = await influxdb.executeQueryForDatabase(query, this.currentDatabase)

        if (results.length > 0) {
          // Extract columns
          this.tableColumns = Object.keys(results[0]).filter(key => key !== '_measurement')

          // 初始化选中的列（如果是第一次加载或者列数变化）
          if (this.selectedColumns.length === 0 || this.selectedColumns.length !== this.tableColumns.length) {
            this.selectedColumns = [...this.tableColumns]
          }

          // Set total count for pagination
          this.pagination.total = results.length

          // Apply pagination
          this.applyPagination(results)
        } else {
          this.tableData = []
          this.tableColumns = []
          this.selectedColumns = []
          this.pagination.total = 0
        }
      } catch (error) {
        this.$message.error('Failed to load data: ' + error.message)
      } finally {
        this.loading = false
      }
    },
    
    buildQuery() {
      const { limit } = this.querySettings
      
      // Always use InfluxQL
      let query = `SELECT * FROM "${this.currentMeasurement}"`
      
      // Add time filter if specified
      const whereConditions = []
      
      if (this.timeFilter.startTime) {
        const start = new Date(this.timeFilter.startTime).toISOString()
        whereConditions.push(`time >= '${start}'`)
      }
      
      if (this.timeFilter.endTime) {
        const end = new Date(this.timeFilter.endTime).toISOString()
        whereConditions.push(`time <= '${end}'`)
      }
      
      if (whereConditions.length > 0) {
        query += ` WHERE ${whereConditions.join(' AND ')}`
      }
      
      // Add sorting
      if (this.sortConfig.prop) {
        const order = this.sortConfig.order === 'descending' ? 'DESC' : 'ASC'
        query += ` ORDER BY ${this.sortConfig.prop} ${order}`
      } else {
        query += ' ORDER BY time ASC'  // Changed to ASC to show oldest first
      }
      
      // Add limit
      query += ` LIMIT ${limit}`
      
      return query
    },
    
    applyPagination(data) {
      const start = (this.pagination.currentPage - 1) * this.pagination.pageSize
      const end = start + this.pagination.pageSize
      this.tableData = data.slice(start, end)
    },
    
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.loadMeasurementData()
    },
    
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.loadMeasurementData()
    },
    
    handleSortChange({ prop, order }) {
      this.sortConfig.prop = prop
      this.sortConfig.order = order
      this.loadMeasurementData()
    },
    
    indexMethod(index) {
      return (this.pagination.currentPage - 1) * this.pagination.pageSize + index + 1
    },
    
    formatTime(time) {
      if (!time) return ''

      // InfluxDB 时间格式可能是：
      // 1. RFC3339 字符串: "2024-01-01T12:00:00.123456789Z"
      // 2. 纳秒时间戳: 1704110400123456789
      // 3. 毫秒时间戳: 1704110400123

      let timeStr = String(time)

      // 如果是 RFC3339 格式（包含纳秒），直接格式化
      if (timeStr.includes('T') && timeStr.includes('Z')) {
        // 提取日期时间部分和纳秒部分
        const match = timeStr.match(/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})\.?(\d*)Z?$/)
        if (match) {
          const [, datetime, nanos] = match
          const date = new Date(datetime + 'Z')

          // 格式化为 YYYY-MM-DD HH:mm:ss.nnnnnnnnn
          const year = date.getFullYear()
          const month = String(date.getMonth() + 1).padStart(2, '0')
          const day = String(date.getDate()).padStart(2, '0')
          const hours = String(date.getHours()).padStart(2, '0')
          const minutes = String(date.getMinutes()).padStart(2, '0')
          const seconds = String(date.getSeconds()).padStart(2, '0')

          // 纳秒部分（9位，不足补0）
          const nanoseconds = nanos ? nanos.padEnd(9, '0') : '000000000'

          return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${nanoseconds}`
        }
      }

      // 如果是纳秒时间戳（19位数字）
      if (/^\d{19}$/.test(timeStr)) {
        const nanoseconds = BigInt(timeStr)
        const milliseconds = Number(nanoseconds / 1000000n)
        const nanos = String(nanoseconds % 1000000n).padStart(6, '0') + '000'

        const date = new Date(milliseconds)
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        const ms = String(date.getMilliseconds()).padStart(3, '0')

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${ms}${nanos.slice(3)}`
      }

      // 如果是微秒时间戳（16位数字）
      if (/^\d{16}$/.test(timeStr)) {
        const microseconds = BigInt(timeStr)
        const milliseconds = Number(microseconds / 1000n)
        const micros = String(microseconds % 1000n).padStart(3, '0')

        const date = new Date(milliseconds)
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        const ms = String(date.getMilliseconds()).padStart(3, '0')

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${ms}${micros}000`
      }

      // 默认使用 Date 解析（毫秒精度）
      const date = new Date(time)
      if (isNaN(date.getTime())) {
        return String(time) // 无法解析，返回原始值
      }

      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      const ms = String(date.getMilliseconds()).padStart(3, '0')

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${ms}000000`
    },
    
    refreshData() {
      this.loadMeasurementData()
    },
    
    async exportCurrentData() {
      if (!this.tableData.length) {
        this.$message.warning('No data to export')
        return
      }
      
      this.$confirm('Select export format', 'Export Data', {
        distinguishCancelAndClose: true,
        confirmButtonText: 'CSV',
        cancelButtonText: 'JSON',
        type: 'info'
      }).then(() => {
        this.exportAsCSV()
      }).catch(action => {
        if (action === 'cancel') {
          this.exportAsJSON()
        }
      })
    },
    
    exportAsCSV() {
      const csv = Papa.unparse(this.tableData)
      const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
      const link = document.createElement('a')
      const url = URL.createObjectURL(blob)
      
      link.setAttribute('href', url)
      link.setAttribute('download', `${this.currentDatabase}_${this.currentMeasurement}_${Date.now()}.csv`)
      link.style.visibility = 'hidden'
      
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      
      this.$message.success('Data exported as CSV')
    },
    
    exportAsJSON() {
      const json = JSON.stringify(this.tableData, null, 2)
      const blob = new Blob([json], { type: 'application/json' })
      const link = document.createElement('a')
      const url = URL.createObjectURL(blob)
      
      link.setAttribute('href', url)
      link.setAttribute('download', `${this.currentDatabase}_${this.currentMeasurement}_${Date.now()}.json`)
      link.style.visibility = 'hidden'
      
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      
      this.$message.success('Data exported as JSON')
    },
    
    showCreateDatabaseDialog() {
      this.newDatabaseForm.name = ''
      this.showNewDatabaseDialog = true
    },
    
    async createDatabase() {
      this.$refs.databaseForm.validate(async (valid) => {
        if (!valid) return
        
        this.creating = true
        try {
          await influxdb.createDatabase(this.newDatabaseForm.name)
          this.$message.success(`Database '${this.newDatabaseForm.name}' created successfully`)
          this.showNewDatabaseDialog = false
          await this.loadDatabases()
        } catch (error) {
          this.$message.error('Failed to create database: ' + error.message)
        } finally {
          this.creating = false
        }
      })
    },
    
    handleDatabaseRightClick(event, database) {
      // Don't show delete for system databases
      if (database === '_internal') {
        return
      }
      
      this.contextMenu = {
        visible: true,
        x: event.clientX,
        y: event.clientY,
        database: database
      }
    },
    
    closeContextMenu() {
      this.contextMenu.visible = false
    },

    // 数据库搜索防抖处理
    onDatabaseSearch() {
      // 搜索是实时的，不需要防抖
      // 如果数据库很多，可以引入 debounce
    },

    // 高亮匹配的文本
    highlightMatch(text) {
      if (!this.databaseSearchQuery) {
        return text
      }

      const query = this.databaseSearchQuery.trim()
      if (!query) {
        return text
      }

      // 使用正则表达式进行大小写不敏感的匹配
      const regex = new RegExp(`(${this.escapeRegex(query)})`, 'gi')
      return text.replace(regex, '<span class="highlight">$1</span>')
    },

    // 转义正则表达式特殊字符
    escapeRegex(str) {
      return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
    },
    
    async deleteDatabase() {
      const database = this.contextMenu.database
      this.closeContextMenu()
      
      try {
        await this.$confirm(
          `Are you sure you want to delete database '${database}'? This action cannot be undone.`,
          'Warning',
          {
            confirmButtonText: 'Delete',
            cancelButtonText: 'Cancel',
            type: 'warning'
          }
        )
        
        await influxdb.deleteDatabase(database)
        this.$message.success(`Database '${database}' deleted successfully`)
        
        // If deleted database was selected, clear selection
        if (this.currentDatabase === database) {
          this.currentDatabase = ''
          this.currentMeasurement = ''
          this.tableData = []
          this.tableColumns = []
        }
        
        await this.loadDatabases()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('Failed to delete database: ' + (error.message || error))
        }
      }
    },
    
    async deleteMeasurement() {
      if (!this.currentMeasurement || !this.currentDatabase) return
      
      try {
        await this.$confirm(
          `Are you sure you want to delete measurement '${this.currentMeasurement}' from database '${this.currentDatabase}'? This action cannot be undone.`,
          'Warning',
          {
            confirmButtonText: 'Delete',
            cancelButtonText: 'Cancel',
            type: 'warning'
          }
        )
        
        await influxdb.deleteMeasurement(this.currentDatabase, this.currentMeasurement)
        this.$message.success(`Measurement '${this.currentMeasurement}' deleted successfully`)
        
        // Clear current measurement and reload
        this.currentMeasurement = ''
        this.tableData = []
        this.tableColumns = []
        await this.loadMeasurements(this.currentDatabase)
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('Failed to delete measurement: ' + (error.message || error))
        }
      }
    },
    
    applyTimeFilter() {
      // Reset to first page when applying filter
      this.pagination.currentPage = 1
      this.loadMeasurementData()
    },
    
    resetFilter() {
      // Clear time filters
      this.timeFilter.startTime = null
      this.timeFilter.endTime = null
      
      // Reset limit to default
      this.querySettings.limit = 10000
      
      // Reset to first page
      this.pagination.currentPage = 1
      
      // Reload data
      this.loadMeasurementData()
      
      this.$message.success('Filter reset to show all data')
    },
    
    visualizeData() {
      // Store the current data in vuex for visualization
      this.$store.commit('SET_QUERY_RESULTS', [{
        database: this.currentDatabase,
        measurement: this.currentMeasurement,
        columns: this.tableColumns,
        data: this.tableData,
        totalCount: this.pagination.total,
        timeFilter: { ...this.timeFilter },
        querySettings: { ...this.querySettings }
      }])

      // Navigate to visualization page
      this.$router.push('/visualization')
      this.$message.success('Data sent to visualization')
    },

    // 列设置相关方法
    selectAllColumns() {
      this.selectedColumns = [...this.tableColumns]
    },

    deselectAllColumns() {
      this.selectedColumns = []
    },

    resetColumnSettings() {
      this.selectedColumns = [...this.tableColumns]
      this.columnSearchQuery = ''
      this.$message.success(this.$t('explorer.columnReset'))
    },

    applyColumnSettings() {
      if (this.selectedColumns.length === 0) {
        this.$message.warning(this.$t('explorer.selectAtLeastOneColumn'))
        return
      }

      this.showColumnSettings = false
      this.columnSearchQuery = ''
      this.$message.success(this.$t('explorer.columnSettingsApplied'))
    },

    cancelColumnSettings() {
      // 恢复之前的状态
      this.showColumnSettings = false
      this.columnSearchQuery = ''
    }
  }
}
</script>

<style scoped>
.database-explorer {
  height: 100%;
  overflow: hidden;
  background: #f8fafc;
}

.database-sidebar {
  background: white;
  border-right: 2px solid #e2e8f0;
  height: 100%;
  display: flex;
  flex-direction: column;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.03);
  position: relative;
}

.sidebar-header {
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 2px solid #e2e8f0;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  flex-shrink: 0;
}

.sidebar-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
  letter-spacing: -0.3px;
}

.header-actions {
  display: flex;
  gap: 8px;
  flex-shrink: 0;
}

.sidebar-header .el-button {
  background: white;
  border-color: #e2e8f0;
  transition: all 0.3s;
}

.sidebar-header .el-button:hover {
  background: #3b82f6;
  border-color: #3b82f6;
  color: white;
}

.sidebar-header .el-button[icon="el-icon-refresh"]:hover {
  transform: rotate(180deg);
}

/* 数据库搜索框样式 */
.database-search {
  padding: 12px 15px;
  background: #f8fafc;
  border-bottom: 1px solid #e2e8f0;
  flex-shrink: 0;
}

.database-search .el-input {
  transition: all 0.3s;
  margin-bottom: 8px;
}

.database-search .el-input:focus-within {
  transform: translateY(-1px);
}

/* 排序选择器样式 */
.sort-selector {
  margin-top: 8px;
}

.sort-selector .el-select {
  width: 100%;
}

.sort-selector .el-option i {
  margin-right: 8px;
  color: #64748b;
}

.database-search >>> .el-input__inner {
  border-radius: 6px;
  border-color: #cbd5e1;
  background: white;
  transition: all 0.3s;
}

.database-search >>> .el-input__inner:focus {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.database-search >>> .el-input__prefix {
  color: #94a3b8;
}

.search-no-result {
  margin-top: 8px;
  padding: 8px;
  text-align: center;
  font-size: 12px;
  color: #94a3b8;
  background: white;
  border-radius: 4px;
  border: 1px dashed #cbd5e1;
}

.database-list {
  flex: 1 1 auto;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 10px;
  min-height: 0;
  height: 100%;
  position: relative;
}

/* Add padding to the menu to ensure last item is visible */
.database-list::after {
  content: '';
  display: block;
  height: 15px;
}

/* Custom scrollbar for database list */
.database-list::-webkit-scrollbar {
  width: 6px;
}

.database-list::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 3px;
}

.database-list::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 3px;
}

.database-list::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}

.database-list .el-menu {
  border-right: none;
  background: transparent;
  height: auto;
  padding-bottom: 15px;
  min-height: calc(100% - 15px);
}

/* Override Element UI menu item styles */
.database-list .el-menu-item {
  height: 40px;
  line-height: 40px;
  padding: 0 15px !important;
}

.database-item {
  width: calc(100% - 8px);
  overflow: hidden;
  margin-bottom: 4px;
  border-radius: 8px;
  transition: all 0.3s;
  box-sizing: border-box;
  display: flex;
  align-items: center;
}

.database-item:last-child {
  margin-bottom: 0;
}

.database-item:hover {
  background: #f1f5f9 !important;
  transform: translateX(4px);
}

.database-item.is-active {
  background: linear-gradient(90deg, #3b82f6 0%, #60a5fa 100%) !important;
  color: white !important;
}

.database-item.is-active i,
.database-item.is-active .database-name {
  color: white !important;
}

.database-item i {
  color: #64748b;
  margin-right: 8px;
}

.database-name {
  display: inline-block;
  max-width: calc(100% - 40px);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
  font-size: 14px;
  font-weight: 500;
}

/* 搜索高亮样式 */
.database-name >>> .highlight {
  background: linear-gradient(120deg, #fef08a 0%, #fde047 100%);
  color: #713f12;
  padding: 2px 4px;
  border-radius: 3px;
  font-weight: 600;
}

.database-item.is-active .database-name >>> .highlight {
  background: rgba(255, 255, 255, 0.3);
  color: white;
  font-weight: 700;
}

/* 数据库计数器样式 */
.database-count {
  position: sticky;
  bottom: 0;
  padding: 10px 15px;
  text-align: center;
  font-size: 12px;
  color: #64748b;
  background: linear-gradient(180deg, transparent 0%, #f8fafc 20%, #f8fafc 100%);
  border-top: 1px solid #e2e8f0;
  margin-top: 8px;
  border-radius: 6px;
  font-weight: 500;
}

.content-header {
  background: white;
  border-bottom: 2px solid #e2e8f0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.03);
  padding: 12px 20px;
  min-height: 60px;
}

.header-info {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
}

.header-title {
  flex: 1;
  min-width: 200px;
}

.header-title h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #1e293b;
  display: flex;
  flex-wrap: wrap;
  align-items: baseline;
  gap: 8px;
}

.measurement-name {
  font-size: 14px;
  color: #64748b;
  font-weight: 400;
}

.database-actions {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 10px;
}

.action-group {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.measurement-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.measurement-label {
  font-size: 14px;
  color: #64748b;
  font-weight: 500;
  white-space: nowrap;
  flex-shrink: 0;
}

.measurement-select {
  min-width: 180px;
  max-width: 250px;
}

.database-actions .el-button {
  white-space: nowrap;
}

.database-actions .el-button-group {
  display: flex;
  flex-wrap: nowrap;
}

.database-actions .el-button-group .el-button {
  font-weight: 500;
}

@media (max-width: 1200px) {
  .header-info {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .database-actions {
    width: 100%;
    justify-content: flex-start;
    margin-top: 10px;
  }
  
  .measurement-group {
    flex: 1;
    min-width: 300px;
  }
  
  .measurement-select {
    flex: 1;
    min-width: 160px;
  }
}

@media (max-width: 768px) {
  .database-actions {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }
  
  .action-group {
    width: 100%;
  }
  
  .measurement-group {
    flex-wrap: wrap;
  }
  
  .measurement-label {
    width: 100%;
    margin-bottom: 5px;
  }
  
  .measurement-select {
    flex: 1;
    min-width: 100%;
    margin-bottom: 5px;
  }
  
  .database-actions .el-button-group {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
  }
  
  .database-actions .el-button-group .el-button {
    flex: 1;
  }
}

.content-main {
  background: #f8fafc;
  padding: 24px;
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

/* Time Filter Styles */
.time-filter-container {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  flex-shrink: 0;
}

.filter-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 20px;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
  min-width: 200px;
}

.filter-label {
  font-size: 14px;
  color: #64748b;
  font-weight: 500;
  white-space: nowrap;
}

.filter-item .el-date-editor {
  flex: 1;
  max-width: 240px;
}

.filter-item .el-input-number {
  flex: 1;
}

.filter-actions {
  display: flex;
  gap: 10px;
  flex-shrink: 0;
}

.filter-actions .el-button {
  font-weight: 500;
}

@media (max-width: 1200px) {
  .filter-row {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-item {
    width: 100%;
  }
  
  .filter-item .el-date-editor {
    max-width: none;
  }
  
  .filter-actions {
    width: 100%;
    justify-content: flex-end;
  }
}

.data-table-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.table-info {
  margin-bottom: 16px;
  padding: 12px;
  background: #f1f5f9;
  border-radius: 8px;
  color: #64748b;
  flex-shrink: 0;
  font-size: 13px;
  font-weight: 500;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.table-info .info-left {
  flex: 1;
  min-width: 200px;
}

.table-info .info-right {
  flex-shrink: 0;
}

.table-wrapper {
  flex: 1;
  min-height: 0;
  overflow: hidden;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.table-wrapper .el-table {
  font-size: 14px;
}

.table-wrapper .el-table th {
  background: #f8fafc !important;
  color: #475569;
  font-weight: 600;
}

.table-wrapper .el-table tr:hover td {
  background: #f8fafc !important;
}

/* 时间列样式 */
.time-cell {
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 13px;
  color: #475569;
  letter-spacing: 0.3px;
}

.pagination-wrapper {
  padding: 20px 0;
  text-align: right;
  flex-shrink: 0;
  border-top: 1px solid #e2e8f0;
  margin-top: 20px;
}

/* Context Menu */
.context-menu {
  position: fixed;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  padding: 8px 0;
  z-index: 2000;
  min-width: 160px;
}

.context-menu-item {
  padding: 10px 16px;
  cursor: pointer;
  font-size: 14px;
  color: #1e293b;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 8px;
}

.context-menu-item:hover {
  background: #f1f5f9;
  color: #ef4444;
}

.context-menu-item i {
  font-size: 16px;
}

/* Empty states */
.el-empty {
  padding: 40px;
}

.el-empty__description {
  color: #64748b;
  font-size: 14px;
}

/* Dialog styles */
.el-dialog {
  border-radius: 12px;
}

.el-dialog__header {
  background: #f8fafc;
  border-bottom: 1px solid #e2e8f0;
  padding: 20px;
  border-radius: 12px 12px 0 0;
}

.el-dialog__title {
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
}

/* 列设置对话框样式 */
.column-settings-dialog .column-settings-content {
  max-height: 500px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.column-settings-dialog .settings-header {
  flex-shrink: 0;
  margin-bottom: 15px;
}

.column-settings-dialog .quick-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  margin-top: 10px;
}

.column-settings-dialog .column-list {
  flex: 1;
  overflow-y: auto;
  min-height: 200px;
  max-height: 350px;
  padding: 10px;
  background: #f8fafc;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.column-settings-dialog .column-list::-webkit-scrollbar {
  width: 6px;
}

.column-settings-dialog .column-list::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 3px;
}

.column-settings-dialog .column-list::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 3px;
}

.column-settings-dialog .column-list::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}

.column-settings-dialog .column-item {
  padding: 8px 12px;
  margin-bottom: 4px;
  background: white;
  border-radius: 6px;
  transition: all 0.2s;
  border: 1px solid transparent;
}

.column-settings-dialog .column-item:hover {
  background: #f1f5f9;
  border-color: #cbd5e1;
  transform: translateX(2px);
}

.column-settings-dialog .column-item:last-child {
  margin-bottom: 0;
}

.column-settings-dialog .column-label {
  margin-left: 8px;
  font-weight: 500;
  color: #1e293b;
}

.column-settings-dialog .column-item .el-tag {
  margin-left: 8px;
}

.column-settings-dialog .no-columns {
  padding: 40px 20px;
  text-align: center;
  color: #94a3b8;
  font-size: 14px;
}

.column-settings-dialog .settings-footer {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #e2e8f0;
  flex-shrink: 0;
}

.column-settings-dialog .selected-count {
  font-size: 13px;
  color: #64748b;
  font-weight: 500;
}
</style>